package cn.shopifymall.spring.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@EnableAspectJAutoProxy 		// 开启AspectJ
@EnableTransactionManagement  	// 开启事务
@Configuration
@ComponentScan("cn.shopifymall.spring")
public class TxConfig {

	/**
	 * 数据源配置
	 */
	@Bean
	public DataSource dataSource() {
		//spring-jdbc提供的最简单的数据源，无连接池管理功能
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setUsername("root");
		dataSource.setPassword("root");
		dataSource.setUrl("jdbc:mysql://localhost:3306/flow?useSSL=false&serverTimezone=Asia/Shanghai");
		dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
		return dataSource;
	}

	@Bean
	public JdbcTemplate jdbcTemplate(DataSource dataSource) {
		return new JdbcTemplate(dataSource);
	}

	/**
	 * 事务管理器，PlatformTransactionManager是通用类型，2003年写的
	 * DataSourceTransactionManager是基于JDBC的实现
	 * JpaTransactionManager是基于JPA的实现
	 */
	@Bean
	public PlatformTransactionManager transactionManager(DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}
}
